package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.file.transfer.core.FileInfo;
import com.stark.file.transfer.core.TfContactInfo;
import com.stark.file.transfer.core.Transferable;
import com.stark.file.transfer.core.TransferableSendManager;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ContactsAdapter;
import flc.ast.adapter.SelPictureAdapter;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.bean.SelectFileBean;
import flc.ast.databinding.ActivitySelFileBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.bean.ContactInfo;
import stark.common.basic.constant.FileType;
import stark.common.basic.utils.ContactUtil;
import stark.common.basic.utils.RxUtil;

public class SelFileActivity extends BaseAc<ActivitySelFileBinding> {

    private SelPictureAdapter pictureAdapter;
    private SelVideoAdapter videoAdapter;
    private ContactsAdapter contactsAdapter;
    private int type = 0;
    private boolean isPicAll = false, isVideoAll = false, isContacts = false;
    private List<SelectFileBean> listSel = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_sel_file;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSelFileBack.setOnClickListener(v -> onBackPressed());
        //图片
        mDataBinding.rvPictureList.setLayoutManager(new GridLayoutManager(mContext, 3));
        pictureAdapter = new SelPictureAdapter();
        mDataBinding.rvPictureList.setAdapter(pictureAdapter);
        pictureAdapter.setOnItemClickListener(this);
        //视频
        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 3));
        videoAdapter = new SelVideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.setOnItemClickListener(this);
        //通讯录
        mDataBinding.rvContactsList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        contactsAdapter = new ContactsAdapter();
        mDataBinding.rvContactsList.setAdapter(contactsAdapter);
        contactsAdapter.setOnItemClickListener(this);

        mDataBinding.tvPicture.setOnClickListener(this);
        mDataBinding.tvVideo.setOnClickListener(this);
        mDataBinding.tvContacts.setOnClickListener(this);
        mDataBinding.tvAllSel.setOnClickListener(this);
        mDataBinding.ivStart.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvPicture://图片
                clearSelection();
                mDataBinding.tvPicture.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvPicture.setBackgroundResource(R.drawable.shape_language_sel);
                type = 0;
                if (pictureAdapter.getValidData() != null) {
                    mDataBinding.rvPictureList.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
                }
                if (isPicAll) {
                    mDataBinding.tvAllSel.setText(getString(R.string.cancel_all_sel));
                } else {
                    mDataBinding.tvAllSel.setText(getString(R.string.all_sel));
                }
                break;
            case R.id.tvVideo://视频
                clearSelection();
                mDataBinding.tvVideo.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvVideo.setBackgroundResource(R.drawable.shape_language_sel);
                type = 1;
                if (videoAdapter.getValidData() != null) {
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
                }
                if (isVideoAll) {
                    mDataBinding.tvAllSel.setText(getString(R.string.cancel_all_sel));
                } else {
                    mDataBinding.tvAllSel.setText(getString(R.string.all_sel));
                }
                break;
            case R.id.tvContacts://通讯录
                clearSelection();
                mDataBinding.tvContacts.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvContacts.setBackgroundResource(R.drawable.shape_language_sel);
                type = 2;
                if (contactsAdapter.getValidData() != null) {
                    mDataBinding.rvContactsList.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
                }
                if (isContacts) {
                    mDataBinding.tvAllSel.setText(getString(R.string.cancel_all_sel));
                } else {
                    mDataBinding.tvAllSel.setText(getString(R.string.all_sel));
                }
                break;
            case R.id.tvAllSel://全选
                switch (type) {
                    case 0://图片
                        clearPicData();
                        if (isPicAll) {
                            getPicData();
                            isPicAll = false;
                            mDataBinding.tvAllSel.setText(getString(R.string.all_sel));
                        } else {
                            addAllPic();
                            isPicAll = true;
                            mDataBinding.tvAllSel.setText(getString(R.string.cancel_all_sel));
                        }
                        break;
                    case 1://视频
                        clearVideoData();
                        if (isVideoAll) {
                            getVideoData();
                            isVideoAll = false;
                            mDataBinding.tvAllSel.setText(getString(R.string.all_sel));
                        } else {
                            addAllVideo();
                            isVideoAll = true;
                            mDataBinding.tvAllSel.setText(getString(R.string.cancel_all_sel));
                        }
                        break;
                    case 2://联系人
                        clearContactsData();
                        if (isContacts) {
                            getContactsData();
                            isContacts = false;
                            mDataBinding.tvAllSel.setText(getString(R.string.all_sel));
                        } else {
                            addAllContacts();
                            isContacts = true;
                            mDataBinding.tvAllSel.setText(getString(R.string.cancel_all_sel));
                        }
                        break;
                }
                long size = 0;
                for (SelectFileBean bean : listSel) {
                    size += bean.getSize();
                }
                mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listSel.size(), ConvertUtils.byte2FitMemorySize(size, 0)));
                isNotSel();
                break;
            case R.id.ivStart://开始传输
                if (listSel.size() == 0) {
                    ToastUtils.showShort(R.string.no_choose_file_transfer_tips);
                } else {
                    List<Transferable> transferableList = new ArrayList<>();
                    List<ContactInfo> contactInfoList = new ArrayList<>();
                    for (SelectFileBean fileBean : listSel) {
                        switch (fileBean.getType()) {
                            case 1://图片
                                FileInfo picFile = new FileInfo();
                                picFile.setFileName(fileBean.getName());
                                picFile.setUriStr(fileBean.getPath());
                                picFile.setFileType(FileType.IMAGE);
                                picFile.setSize(fileBean.getSize());
                                transferableList.add(picFile);
                                break;
                            case 2://视频
                                FileInfo videoFile = new FileInfo();
                                videoFile.setFileName(fileBean.getName());
                                videoFile.setUriStr(fileBean.getPath());
                                videoFile.setFileType(FileType.VIDEO);
                                videoFile.setSize(fileBean.getSize());
                                transferableList.add(videoFile);
                                break;
                            case 3://联系人
                                ContactInfo contactInfo = new ContactInfo();
                                contactInfo.setName(fileBean.getName());
                                contactInfo.setPhone(fileBean.getPath());
                                contactInfoList.add(contactInfo);
                                TfContactInfo tfContactInfo = new TfContactInfo(contactInfoList);
                                transferableList.add(tfContactInfo);
                                break;
                            default:
                                break;
                        }
                    }
                    TransferableSendManager.getInstance().setTransferables(transferableList);
                    FileSendShowQrActivity.listSend = listSel;
                    startActivity(FileSendShowQrActivity.class);
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == pictureAdapter) {
            SelectFileBean bean = new SelectFileBean();
            bean.setType(1);
            bean.setName(pictureAdapter.getItem(position).getMediaName());
            bean.setPath(pictureAdapter.getItem(position).getUri());
            bean.setSize(pictureAdapter.getItem(position).getSize());
            if (pictureAdapter.getItem(position).isChecked()) {
                pictureAdapter.getItem(position).setChecked(false);
                listSel.remove(bean);
            } else {
                pictureAdapter.getItem(position).setChecked(true);
                listSel.add(bean);
            }
        } else if (adapter == videoAdapter) {
            SelectFileBean bean = new SelectFileBean();
            bean.setType(2);
            bean.setName(videoAdapter.getItem(position).getMediaName());
            bean.setPath(videoAdapter.getItem(position).getUri());
            bean.setSize(videoAdapter.getItem(position).getSize());
            if (videoAdapter.getItem(position).isChecked()) {
                videoAdapter.getItem(position).setChecked(false);
                listSel.remove(bean);
            } else {
                videoAdapter.getItem(position).setChecked(true);
                listSel.add(bean);
            }
        } else if (adapter == contactsAdapter) {
            SelectFileBean bean = new SelectFileBean();
            bean.setType(3);
            bean.setName(contactsAdapter.getItem(position).getName());
            bean.setPath(contactsAdapter.getItem(position).getPhone());
            bean.setSize(contactsAdapter.getItem(position).getPhone().length());
            if (contactsAdapter.getItem(position).isSelected()) {
                contactsAdapter.getItem(position).setSelected(false);
                listSel.remove(bean);
            } else {
                contactsAdapter.getItem(position).setSelected(true);
                listSel.add(bean);
            }
        }
        adapter.notifyDataSetChanged();
        isNotSel();
        long size = 0;
        for (SelectFileBean bean : listSel) {
            size += bean.getSize();
        }
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listSel.size(), ConvertUtils.byte2FitMemorySize(size, 0)));
    }

    @Override
    protected void initData() {
        getPicData();
        getVideoData();
        getContactsData();
        if (pictureAdapter.getValidData() != null) {
            mDataBinding.rvPictureList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
        }
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, 0, "0M"));
    }

    //获取视频和图片数据
    private void getPicData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    pictureAdapter.setList(selectMediaEntities);
                }
            }
        });
    }

    //获取视频和图片数据
    private void getVideoData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    videoAdapter.setList(selectMediaEntities);
                }
            }
        });
    }

    //获取联系人列表
    private void getContactsData() {
        RxUtil.create(new RxUtil.Callback<List<ContactInfo>>() {
            @SuppressLint("MissingPermission")
            @Override
            public void doBackground(ObservableEmitter<List<ContactInfo>> emitter) {
                List<ContactInfo> contactInfoList = ContactUtil.getAllContact();
                emitter.onNext(contactInfoList);
            }

            @Override
            public void accept(List<ContactInfo> contactInfoList) {
                if (contactInfoList != null && contactInfoList.size() != 0) {
                    contactsAdapter.setList(contactInfoList);
                }
            }
        });
    }

    //判断是否没有选择
    private void isNotSel() {
        if (listSel.size() != 0) {
            mDataBinding.ivStart.setImageResource(R.drawable.kaishichuanshu22);
        } else {
            mDataBinding.ivStart.setImageResource(R.drawable.kaishichuanshu11);
        }
    }

    //清空选中图片
    private void clearPicData() {
        Iterator<SelectFileBean> iterator = listSel.iterator();
        while (iterator.hasNext()) {
            SelectFileBean bean = iterator.next();
            if (bean.getType() == 1) {
                iterator.remove();
            }
        }
    }

    //全选视频
    private void addAllPic() {
        for (SelectMediaEntity validDatum : pictureAdapter.getValidData()) {
            SelectFileBean bean = new SelectFileBean();
            bean.setType(1);
            bean.setName(validDatum.getMediaName());
            bean.setPath(validDatum.getUri());
            bean.setSize(validDatum.getSize());
            listSel.add(bean);
            validDatum.setChecked(true);
        }
        pictureAdapter.notifyDataSetChanged();
    }

    //清空选中视频
    private void clearVideoData() {
        Iterator<SelectFileBean> iterator = listSel.iterator();
        while (iterator.hasNext()) {
            SelectFileBean bean = iterator.next();
            if (bean.getType() == 2) {
                iterator.remove();
            }
        }
    }

    //全选图片
    private void addAllVideo() {
        for (SelectMediaEntity validDatum : videoAdapter.getValidData()) {
            SelectFileBean bean = new SelectFileBean();
            bean.setType(2);
            bean.setName(validDatum.getMediaName());
            bean.setPath(validDatum.getUri());
            bean.setSize(validDatum.getSize());
            listSel.add(bean);
            validDatum.setChecked(true);
        }
        videoAdapter.notifyDataSetChanged();
    }

    //清空选中联系人
    private void clearContactsData() {
        Iterator<SelectFileBean> iterator = listSel.iterator();
        while (iterator.hasNext()) {
            SelectFileBean bean = iterator.next();
            if (bean.getType() == 3) {
                iterator.remove();
            }
        }
    }

    //全选联系人
    private void addAllContacts() {
        for (ContactInfo validDatum : contactsAdapter.getValidData()) {
            SelectFileBean bean = new SelectFileBean();
            bean.setType(3);
            bean.setName(validDatum.getName());
            bean.setPath(validDatum.getPhone());
            bean.setSize(validDatum.getPhone() == null ? 0 : validDatum.getPhone().length());
            listSel.add(bean);
            validDatum.setSelected(true);
        }
        contactsAdapter.notifyDataSetChanged();
    }

    private void clearSelection() {
        mDataBinding.tvPicture.setTextColor(Color.parseColor("#80313131"));
        mDataBinding.tvPicture.setBackgroundResource(0);
        mDataBinding.tvVideo.setTextColor(Color.parseColor("#80313131"));
        mDataBinding.tvVideo.setBackgroundResource(0);
        mDataBinding.tvContacts.setTextColor(Color.parseColor("#80313131"));
        mDataBinding.tvContacts.setBackgroundResource(0);
        mDataBinding.rvPictureList.setVisibility(View.GONE);
        mDataBinding.rvVideoList.setVisibility(View.GONE);
        mDataBinding.rvContactsList.setVisibility(View.GONE);
        mDataBinding.tvFileNoData.setVisibility(View.GONE);
    }

}